package com.zyl.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhaoyl
 * @date 2024/5/15 15:37
 * @description 说明
 * Lock和Condition多线程等待通知，顺序执行
 * A执行完调用B,B执行完调用C,C执行完调用A
 * await和signal
 */
public class ConditionTest {
    public static void main(String[] args) {
        DataC data = new DataC();
        //开启线程
        new Thread(()->{
            for (int i=0;i<10;i++){
            data.printA();
            }
        },"线程A").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                data.printB();
            }
        },"线程B").start();
        new Thread(()->{
            for (int i=0;i<10;i++){
                data.printC();
            }
        },"线程C").start();

    }
}

//资源类
class DataC{
    //同步锁
    private Lock lock = new ReentrantLock();
    //三个监视器
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();
    //状态值；如果是1则A执行，如果是2则B执行，如果是3则C执行，
    private  int status =1;
    public void printA(){
        lock.lock();
        //业务，判断->执行->通知
        try {
            //条件
            while (status!=1){
                //A等待
                conditionA.await();
            }
            System.out.println("当前"+Thread.currentThread().getName()+"AAA=>"+status);
            status =2;
            conditionB.signal();//唤醒B
        }catch (Exception e){
        }finally {
            lock.unlock();
        }
    };
    public void printB(){
        lock.lock();
        //业务，判断->执行->通知
        try {
            while (status!=2){
                //B等待
                conditionB.await();
            }
            System.out.println("当前"+Thread.currentThread().getName()+"BBB=>"+status);
            status =3;
            conditionC.signal();//唤醒C
        }catch (Exception e){
        }finally {
            lock.unlock();
        }
    };
    public void printC(){
        lock.lock();
        //业务，判断->执行->通知
        try {

            while (status!=3){
                //C等待
                conditionC.await();
            }
            System.out.println("当前"+Thread.currentThread().getName()+"CCC=>"+status);
            status =1;
            conditionA.signal();//唤醒A
        }catch (Exception e){
        }finally {
            lock.unlock();
        }
    };
}